package view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import org.bushe.swing.event.EventBus;

import model.Player;
import constants.Events;

/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
@SuppressWarnings("serial")
public class NewGameView extends javax.swing.JFrame implements KeyListener{
    private AbstractAction okAction;
    private AbstractAction cancelAction;
    private AbstractAction checkP1Action;
    private AbstractAction checkP2Action;
    private AbstractAction check4Action;
    private AbstractAction p3CheckAction;
    private JButton cancelButton;
    private JButton okButton;
    private JComboBox p4Color;
    private JComboBox p3Color;
    private JComboBox p2Color;
    private JComboBox p1Color;
    private JTextField p4Name;
    private JTextField p3Name;
    private JTextField p2Name;
    private JTextField p1Name;
    private JCheckBox checkP1;
    private JCheckBox checkP4;
    private JCheckBox checkP3;
    private JCheckBox checkP2;

    private Player[] players;

    private JCheckBox[]  checkboxes = null;
    private JTextField[] textfields = null;
    private JComboBox[]  comboboxes = null;

    public NewGameView() {
        super();
        initGUI();
        setVisible(true);
        setLocationRelativeTo(null);

        JCheckBox[]  checkboxes2 = {checkP1, checkP2, checkP3, checkP4};
        JTextField[] textfields2 = {p1Name, p2Name, p3Name, p4Name};
        JComboBox[]  comboboxes2 = {p1Color, p2Color, p3Color, p4Color};

        checkboxes = checkboxes2;
        textfields = textfields2;
        comboboxes = comboboxes2;

        for(JCheckBox c: checkboxes)
            c.setSelected(true);
        setFocusable(true);
        addKeyListener(this);

    }

    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(null);
            getContentPane().setBackground(new java.awt.Color(255, 255, 255));
            this.setTitle("New game settings");
            {
                checkP1 = new JCheckBox();
                getContentPane().add(checkP1);
                checkP1.setText("Player 1");
                checkP1.setBounds(12, 25, 74, 20);
                checkP1.setAction(getCheckP1Action());
            }
            {
                checkP2 = new JCheckBox();
                getContentPane().add(checkP2);
                checkP2.setText("Player 2");
                checkP2.setBounds(12, 64, 74, 20);
                checkP2.setAction(getCheckP2Action());
            }
            {
                checkP3 = new JCheckBox();
                getContentPane().add(checkP3);
                checkP3.setText("Player 3");
                checkP3.setBounds(12, 106, 74, 20);
                checkP3.setAction(getP3CheckAction());
            }
            {
                checkP4 = new JCheckBox();
                getContentPane().add(checkP4);
                checkP4.setText("Player 4");
                checkP4.setBounds(12, 147, 74, 20);
                checkP4.setAction(getCheck4Action());
            }
            {
                p1Name = new JTextField();
                getContentPane().add(p1Name);
                p1Name.setText("Player1");
                p1Name.setBounds(91, 24, 161, 22);
            }
            {
                p2Name = new JTextField();
                getContentPane().add(p2Name);
                p2Name.setText("Player2");
                p2Name.setBounds(91, 63, 161, 22);
            }
            {
                p3Name = new JTextField();
                getContentPane().add(p3Name);
                p3Name.setText("Player3");
                p3Name.setBounds(91, 105, 161, 22);
            }
            {
                p4Name = new JTextField();
                getContentPane().add(p4Name);
                p4Name.setText("Player4");
                p4Name.setBounds(91, 146, 161, 22);
            }
            {
                ComboBoxModel p1ColorModel =
                    new DefaultComboBoxModel(
                            new String[] { "red", "green", "blue", "yellow" });
                p1Color = new JComboBox();
                getContentPane().add(p1Color);
                p1Color.setModel(p1ColorModel);
                p1Color.setBounds(292, 24, 67, 22);
            }
            {
                ComboBoxModel p2ColorModel =
                    new DefaultComboBoxModel(
                            new String[] { "blue", "red", "green", "yellow" });
                p2Color = new JComboBox();
                getContentPane().add(p2Color);
                p2Color.setModel(p2ColorModel);
                p2Color.setBounds(292, 63, 67, 22);
            }
            {
                ComboBoxModel p3ColorModel =
                    new DefaultComboBoxModel(
                            new String[] { "green", "red", "blue", "yellow" });
                p3Color = new JComboBox();
                getContentPane().add(p3Color);
                p3Color.setModel(p3ColorModel);
                p3Color.setBounds(292, 105, 67, 22);
            }
            {
                ComboBoxModel p4ColorModel =
                    new DefaultComboBoxModel(
                            new String[] { "yellow", "red", "blue", "green" });
                p4Color = new JComboBox();
                getContentPane().add(p4Color);
                p4Color.setModel(p4ColorModel);
                p4Color.setBounds(292, 146, 67, 22);
            }
            {
                okButton = new JButton();
                getContentPane().add(okButton);
                okButton.setText("OK");
                okButton.setBounds(300, 271, 59, 22);
                okButton.setAction(getOkAction());
            }
            {
                cancelButton = new JButton();
                getContentPane().add(cancelButton);
                cancelButton.setText("Cancel");
                cancelButton.setBounds(214, 271, 75, 22);
                cancelButton.setAction(getCancelAction());
            }
            pack();
            this.setSize(400, 340);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean validChecks() {
        int i = 0;
        if(checkP1.isSelected())
            i++;
        if(checkP2.isSelected())
            i++;
        if(checkP3.isSelected())
            i++;
        if(checkP4.isSelected())
            i++;
        if(i > 0)
            return true;
        else
            return false;
    }

    private boolean hasValidData() {
        String p1 = p1Color.getSelectedItem().toString();
        String p2 = p2Color.getSelectedItem().toString();
        String p3 = p3Color.getSelectedItem().toString();
        String p4 = p4Color.getSelectedItem().toString();

        if(!p1.equals(p2) && !p1.equals(p3) && !p1.equals(p4) &&
                !p2.equals(p3) && !p2.equals(p4) && !p3.equals(p4) && validChecks() ) {
            return true;
        }
        else
            return false;
    }

    private AbstractAction getCheckP1Action() {
        if(checkP1Action == null) {
            checkP1Action = new AbstractAction("Player 1", null) {
                public void actionPerformed(ActionEvent evt) {
                    if(!checkP1.isSelected()) {
                        p1Name.setEnabled(false);
                        p1Color.setEnabled(false);
                    } else {
                        p1Name.setEnabled(true);
                        p1Color.setEnabled(true);
                    }
                }
            };
        }
        return checkP1Action;
    }

    private AbstractAction getCheckP2Action() {
        if(checkP2Action == null) {
            checkP2Action = new AbstractAction("Player 2", null) {
                public void actionPerformed(ActionEvent evt) {
                    if(!checkP2.isSelected()) {
                        p2Name.setEnabled(false);
                        p2Color.setEnabled(false);
                    } else {
                        p2Name.setEnabled(true);
                        p2Color.setEnabled(true);
                    }
                }
            };
        }
        return checkP2Action;
    }


    private AbstractAction getP3CheckAction() {
        if(p3CheckAction == null) {
            p3CheckAction = new AbstractAction("Player 3", null) {
                public void actionPerformed(ActionEvent evt) {
                    if(!checkP3.isSelected()) {
                        p3Name.setEnabled(false);
                        p3Color.setEnabled(false);
                    } else {
                        p3Name.setEnabled(true);
                        p3Color.setEnabled(true);
                    }
                }
            };
        }
        return p3CheckAction;
    }

    private AbstractAction getCheck4Action() {
        if(check4Action == null) {
            check4Action = new AbstractAction("Player 4", null) {
                public void actionPerformed(ActionEvent evt) {
                    if(!checkP4.isSelected()) {
                        p4Name.setEnabled(false);
                        p4Color.setEnabled(false);
                    } else {
                        p4Name.setEnabled(true);
                        p4Color.setEnabled(true);
                    }
                }
            };
        }
        return check4Action;
    }

    private AbstractAction getCancelAction() {
        if(cancelAction == null) {
            cancelAction = new AbstractAction("Cancel", null) {
                public void actionPerformed(ActionEvent evt) {
                    setVisible(false);
                }
            };
        }
        return cancelAction;
    }

    private AbstractAction getOkAction() {
        if(okAction == null) {
            okAction = new AbstractAction("OK", null) {
                public void actionPerformed(ActionEvent evt) {
                    if(!hasValidData()) {
                        JOptionPane.showMessageDialog(null, "The information that you have entered is not valid");
                    }
                    else {

                    /*
                     * Essentially, what we do here is to build the list of players.
                     * By the time the user clicks "Ok", all mandatory fields should
                     * already be set, and this is then condensed into a HashMap, which
                     * is in turn passed on to the Model.
                     */

                    players = new Player[4];

                    for(int i = 0; i < 4; i++) {

                        if(!checkboxes[i].isSelected())
                            continue;

                        Color color = Color.blue;

                        /*
                         * Yes, this is ugly, but I could not use Enums directly in
                         * the comboboxes and get it to render properly, so... :(
                         */
                        String selectedColor = (String)comboboxes[i].getSelectedItem();
                        if(selectedColor.equals("blue"))
                            color = Color.blue;
                        else if (selectedColor.equals("yellow"))
                            color = Color.yellow;
                        else if (selectedColor.equals("red"))
                        color = Color.red;
                        else if (selectedColor.equals("green"))
                            color = Color.green;

                        players[i] = new Player(textfields[i].getText(), color, i);
                    }

                    EventBus.publish(Events.NEWGAME.toString(), players);
                    setVisible(false);
                    }
                }
            };
        }
        return okAction;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        Character c = e.getKeyChar();
        if(c.equals('\n')) {
            okButton.doClick();
        }
        System.out.println(e.getKeyCode());
        if(e.getKeyCode() == 27)
            cancelButton.doClick();

    }

    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void keyTyped(KeyEvent e) {}
}
